package hn.security.configuration;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component("userDetailsService")
public class UserDetailsServiceImpl implements UserDetailsService {

    private static final Logger logger = LoggerFactory.getLogger(UserDetailsServiceImpl.class);

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        String error;
        if (username == null || "".equals(username)) {
            error = "username is null or empty";
            logger.error(error);
            //注意这里没有指定异常类型默认是用户不存在
            throw new InternalAuthenticationServiceException(error);
        }
        List<GrantedAuthority> grantedAuthorityList = new ArrayList<>();
        grantedAuthorityList.add(new SimpleGrantedAuthority("super"));
        grantedAuthorityList.add(new SimpleGrantedAuthority("system"));
        grantedAuthorityList.add(new SimpleGrantedAuthority("manager"));
        grantedAuthorityList.add(new SimpleGrantedAuthority("customer"));

        // {noop}表示明文密码
        return new User("username", "{noop}password", true, true, true, true, grantedAuthorityList);

    }
}
